#!/bin/bash
# CodeQL automated scanning pipeline startup script

set -e

# Script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Logging functions
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Check dependencies
check_dependencies() {
    log_info "Checking dependencies..."
    
    # Check Python
    if ! command -v python3 &> /dev/null; then
        log_error "Python3 not installed"
        exit 1
    fi
    
    # Check CodeQL
    if [ ! -f "/Users/winegee/Desktop/mcp_security/codeql/codeql" ]; then
        log_error "CodeQL CLI 未Found，请检查路径: /Users/winegee/Desktop/mcp_security/codeql/codeql"
        exit 1
    fi
    
    # Check virtual environment
    if [ ! -d "venv" ]; then
        log_warning "虚拟环境does not exist，正在创建..."
        python3 -m venv venv
        source venv/bin/activate
        pip install -r requirements.txt
    else
        source venv/bin/activate
    fi
    
    log_success "Dependency check completed"
}

# Create necessary directories
create_directories() {
    log_info "Create necessary directories..."
    
    mkdir -p results
    mkdir -p reports
    mkdir -p databases
    mkdir -p logs
    
    log_success "Directory creation completed"
}

# Show help information
show_help() {
    echo "CodeQL automated scanning pipeline"
    echo ""
    echo "Usage: $0 [Options]"
    echo ""
    echo "Options:"
    echo "  run                Run complete scanning pipeline"
    echo "  run-once           Execute one scan immediately"
    echo "  schedule           Start scheduler"
    echo "  analyze            Analyze scan results"
    echo "  preview            Preview projects to be scanned"
    echo "  clean              Clean up temporary files"
    echo "  status             Show pipeline status"
    echo "  help               Show this help information"
    echo ""
    echo "Examples:"
    echo "  $0 run                    # Run complete scan"
    echo "  $0 run --languages Python TypeScript --max-projects 5  # Scan specific languages with limit"
    echo "  $0 run-once --languages Python --max-projects 3  # One-time scan with specific settings"
    echo "  $0 schedule               # Start scheduled scanning"
    echo "  $0 analyze                # Analyze results"
    echo "  $0 preview --languages Go Rust --max-projects 2  # Preview specific languages"
}

# Run complete scan
run_pipeline() {
    log_info "Starting CodeQL scanning pipeline..."
    source venv/bin/activate
    python codeql_pipeline.py "${@:2}"
    log_success "Scanning pipeline completed"
}

# Execute one scan immediately
run_once() {
    log_info "Executing one-time scan..."
    source venv/bin/activate
    python scheduler.py --run-once "${@:2}"
    log_success "One-time scan completed"
}

# Start scheduler
start_scheduler() {
    log_info "Start scheduler..."
    source venv/bin/activate
    python scheduler.py --start-scheduler
}

# Analyze results
analyze_results() {
    log_info "Analyze scan results..."
    source venv/bin/activate
    python result_analyzer.py --results-dir results
    log_success "结果Analysis completed"
}

# Preview projects
preview_projects() {
    log_info "Preview projects to be scanned..."
    source venv/bin/activate
    python codeql_pipeline.py --dry-run
}

# Clean up temporary files
cleanup() {
    log_info "Clean up temporary files..."
    
    # 清理数据库文件
    if [ -d "databases" ]; then
        rm -rf databases/*
        log_info "已清理数据库文件"
    fi
    
    # 清理Log files（保留最近7天）
    if [ -d "logs" ]; then
        find logs -name "*.log" -mtime +7 -delete
        log_info "已清理旧Log files"
    fi
    
    log_success "清理完成"
}

# 显示状态
show_status() {
    log_info "Pipeline status:"
    echo ""
    
    # Check configuration file
    if [ -f "config.yaml" ]; then
        log_success "Configuration file: exists"
    else
        log_error "Configuration file: not found"
    fi
    
    # Check results directory
    if [ -d "results" ]; then
        result_count=$(find results -name "*.sarif" | wc -l)
        log_success "Scan results: $result_count SARIF files"
    else
        log_warning "Scan results: 无"
    fi
    
    # Check reports directory
    if [ -d "reports" ]; then
        report_count=$(find reports -name "*.html" -o -name "*.json" | wc -l)
        log_success "Analysis reports: $report_count files"
    else
        log_warning "Analysis reports: none"
    fi
    
    # Check databases directory
    if [ -d "databases" ]; then
        db_count=$(find databases -type d -mindepth 2 | wc -l)
        log_success "CodeQL databases: $db_count"
    else
        log_warning "CodeQL databases: none"
    fi
    
    # Check logs directory
    if [ -d "logs" ]; then
        log_count=$(find logs -name "*.log" | wc -l)
        log_success "Log files: $log_count projects"
    else
        log_warning "Log files: none"
    fi
}

# Main function
main() {
    case "${1:-help}" in
        "run")
            check_dependencies
            create_directories
            run_pipeline "$@"
            ;;
        "run-once")
            check_dependencies
            create_directories
            run_once "$@"
            ;;
        "schedule")
            check_dependencies
            create_directories
            start_scheduler
            ;;
        "analyze")
            analyze_results
            ;;
        "preview")
            preview_projects
            ;;
        "clean")
            cleanup
            ;;
        "status")
            show_status
            ;;
        "help"|"--help"|"-h")
            show_help
            ;;
        *)
            log_error "未知命令: $1"
            echo ""
            show_help
            exit 1
            ;;
    esac
}

# 执行Main function
main "$@"
